#!/bin/bash


init(){
for i in {5,17,22,27} 
do
    if [[ ! -e /sys/class/gpio/gpio$i ]]; then 
        echo $i > /sys/class/gpio/export
    fi
    cd /sys/class/gpio/gpio$i
    if [[ `cat direction` != "out" ]]; then 
        echo out > direction
    fi
done

for i in {6,13,19,26} 
do
    if [[ ! -e /sys/class/gpio/gpio$i ]]; then 
        echo $i > /sys/class/gpio/export
    fi
    cd /sys/class/gpio/gpio$i
    if [[ `cat direction` != "out" ]]; then 
        echo in > direction
    fi
done


}

LED_allon(){
echo "allon"
for i in {5,17,22,27} 
do
    echo 1 > /sys/class/gpio/gpio$i/value
done
}

LED_alldown(){
echo "alldown"
for i in {5,17,22,27} 
do  
    echo 0 > /sys/class/gpio/gpio$i/value
done
}


init
#LED_allon
#sleep 5s
#LED_alldown

LED_change(){

echo $1 > /sys/class/gpio/gpio$2/value

}


KEY1=("6" "1" "1" "5")
KEY2=("13" "1" "2" "22")
KEY3=("19" "1" "3" "27")
KEY4=("26" "1" "4" "17")


while [ 1 ] ;do

    state=`cat /sys/class/gpio/gpio${KEY1[0]}/value`
    if [[ $state == "1" && $state != ${KEY1[1]} ]]; then
        echo "key${KEY1[2]} up"
        LED_change "0" ${KEY1[3]}
        KEY1[1]="1"
    elif [[ $state == "0" && $state != ${KEY1[1]} ]]; then
        echo "key${KEY1[2]} down"
        KEY1[1]="0"
        LED_change "1" ${KEY1[3]}
    fi

    
    

    state=`cat /sys/class/gpio/gpio${KEY2[0]}/value`
    if [[ $state == "1" && $state != ${KEY2[1]} ]]; then
        echo "key${KEY2[2]} up"
        LED_change "0" ${KEY2[3]}
        KEY2[1]="1"
    elif [[ $state == "0" && $state != ${KEY2[1]} ]]; then
        echo "key${KEY2[2]} down"
        KEY2[1]="0"
        LED_change "1" ${KEY2[3]}
    fi


    state=`cat /sys/class/gpio/gpio${KEY3[0]}/value`
    if [[ $state == "1" && $state != ${KEY3[1]} ]]; then
        echo "key${KEY3[2]} up"
        LED_change "0" ${KEY3[3]}
        KEY3[1]="1"
    elif [[ $state == "0" && $state != ${KEY3[1]} ]]; then
        echo "key${KEY3[2]} down"
        LED_change "1" ${KEY3[3]}
        KEY3[1]="0"
    fi

    state=`cat /sys/class/gpio/gpio${KEY4[0]}/value`
    if [[ $state == "1" && $state != ${KEY4[1]} ]]; then
        echo "key${KEY4[2]} up"
        LED_change "0" ${KEY4[3]}
        KEY4[1]="1"
    elif [[ $state == "0" && $state != ${KEY4[1]} ]]; then
        echo "key${KEY4[2]} down"
        LED_change "1" ${KEY4[3]}
        KEY4[1]="0"
    fi

done

    









